package com.las.bot.cmd.xf;

import cn.hutool.core.io.unit.DataUnit;
import com.google.common.collect.Sets;
import com.jfinal.kit.StrKit;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseCommand;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import com.utils.DateUtils;
import com.utils.SpiderHtml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

@BotCmd(funName = "新番订阅")
@Component(value = "xFCommand")
public class XFCommand extends BaseCommand {

    private Logger logger = LoggerFactory.getLogger(XFCommand.class);


    public XFCommand() {
        super("今日新番", "今日番剧", "今日动漫", "新番订阅");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        StringBuilder sb = new StringBuilder();
        String url = "https://www.yxdmgo.com/";
        Set<String> keys = Sets.newHashSet();
        keys.add("今天");
        // 顺便把昨天的也列在里面
        Date now = new Date();
        Date date = DateUtils.addDay(now, -1);
        String formatYMD = DateUtils.formatYMD(date);
        String[] dsp = formatYMD.split("-");
        String day = fillDay(dsp[1] + "-" + dsp[2]);
        keys.add(day);
        String info = SpiderHtml.spiderByKeyWithHtml(url, keys);
        String[] split = info.split("\n");
        for (String str : split) {
            String[] ems = str.split("<a");
            if (ems.length > 0) {
                String name = SpiderHtml.guoHtml(ems[ems.length - 1]);
                String title = name.split("href=")[0];
                String newStr = title.replaceAll("title=", "").replaceAll("target=\"_blank","");
                if(StrKit.isBlank(newStr)){
                    continue;
                }
                title = newStr.substring(1, newStr.length() - 2);
                sb.append(title).append("\n");
            }
        }
        if (StrUtils.isNotBlank(sb.toString())) {
            logger.info(sb.toString());
            CmdUtil.sendMessage(sb.toString(), userId, id, type);
        }
    }

    /**
     * 爬取776动漫的日期是 8-1 需要补充0
     *
     * @param font 8-1
     * @return 08-01
     */
    private String fillDay(String font) {
        if (StrUtils.isBlank(font)) {
            return null;
        }
        String md = null;
        try {
            String[] split = font.split("-");
            int m = Integer.parseInt(split[0]);
            int d = Integer.parseInt(split[1]);
            md = String.format("%02d", m) + "-" + String.format("%02d", d);
        } catch (Exception e) {
            logger.error("转换日期出错：" + e.getMessage());
        }
        return md;
    }

}
